import { defineStore } from 'pinia'
import { ref } from 'vue'

interface user {
  username: string
  nickname: string
  token: string
  user_id: string
}

export const useUserStore = defineStore('user', () => {
  const user = ref<user>({
    username: '',
    nickname: '',
    user_id: '',
    token: ''
  })

  const setUserInfo = (data: user) => {
    user.value = data
    localStorage.setItem('user', JSON.stringify(data))
  }

  const getUserInfo = (): user => {
    const res = localStorage.getItem('user')
    if (res) {
      return JSON.parse(res || '')
    } else {
      return {
        username: '',
        nickname: '',
        token: '',
        user_id: ''
      }
    }
  }
  const getUserId = (): string => {
    return getUserInfo().user_id
  }
  user.value = getUserInfo()
  return {
    user,
    setUserInfo,
    getUserInfo,
    getUserId
  }
})
